package handler

import (
	"crypto/md5"
	"fmt"
	"io"
	"net/http"
	"path"
	"path/filepath"
	"time"
	"zero-cloud-disk/api/models"
	"zero-cloud-disk/common/response"
	"zero-cloud-disk/plugins/ali"

	"github.com/zeromicro/go-zero/rest/httpx"
	"zero-cloud-disk/api/internal/logic"
	"zero-cloud-disk/api/internal/svc"
	"zero-cloud-disk/api/internal/types"
)

func FileUploadHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.FileUploadReq
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		file, fileHeader, err := r.FormFile("file")
		if err != nil {
			return
		}
		// 判断文件是否存在
		b := make([]byte, fileHeader.Size)
		_, err = file.Read(b)
		if err != nil {
			return
		}
		hash := fmt.Sprintf("%x", md5.Sum(b))
		rp := new(models.RepositoryPool)
		has, err := svcCtx.Engine.Where("hash = ?", hash).Get(rp)
		if err != nil {
			return
		}
		if has {
			response.Response(w, r, &types.FileUploadRes{Identity: rp.Identity, Ext: rp.Ext, Name: rp.Name}, err)
			return
		}
		// 创建文件 COS
		fileObj, err := fileHeader.Open()
		byteData, err := io.ReadAll(fileObj)
		// 生成随机文件名
		filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(fileHeader.Filename))
		filePath, _, err := ali.UploadImageOss(byteData, filename, "cloud")
		if err != nil {
			return
		}

		// 往 logic 中传递
		req.Name = filename
		req.Ext = path.Ext(filename)
		req.Hash = hash
		req.Size = fileHeader.Size
		req.Path = filePath

		l := logic.NewFileUploadLogic(r.Context(), svcCtx)
		resp, err := l.FileUpload(&req)
		response.Response(w, r, resp, err)
	}
}
